// 生产者

var redis = require('redis')
var bluebird = require('bluebird')
var EventEmitter = require('events')
var client = redis.createClient('6379', '127.0.0.1')
client.on('error', err => console.log(err))
client.on('ready', () => console.log('ready'))
bluebird.promisifyAll(redis.RedisClient.prototype)
bluebird.promisifyAll(redis.Multi)
class Producer extends EventEmitter {
  constructor () {
    super()
    this.status = 'ready'
    this.id = 40000000
  }
}
var producer = new Producer()
producer.on('pause', function() {
  if (this.status === 'begin') {
    this.status = 'pause'
    console.log(`Producer will pause, current id: ${this.id}`)
  }
})
producer.on('resume', function() {
  if (this.status === 'pause') {
    this.status = 'begin'
    this.emit('begin')
  }

})
producer.on('begin', async function() {
  this.status = 'begin'
  while(true) {
    // 如果当前状态为 pause,暂停生产
    if (this.status == 'pause') {
      break
    }
    var msg = this.id
    // // 写入 redis Redis链表类似JS数组，lpush向链表中添加值
    let value = await client.lpushAsync('test', msg)
    console.log('this id', this.id)
    ++this.id
  }
})
async function getListLength() {
 var length = await client.LLENAsync('test')
 console.log('getListLength', length)
  // 当累计的数量达到10000时，暂停生产
  if (length > 10000) {
    producer.emit('pause')
  }
  console.log('producer length: ', length)
  return length
}
producer.emit('begin')
setInterval(getListLength, 10000)